package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.domain.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.domain.dto.IotMsgNotifyData;
import com.zzyl.nursing.domain.dto.IotMsgService;
import com.zzyl.nursing.service.IDeviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Map;

/**
 * 设备数据表Service业务层处理
 *
 * @author Lcc
 * @date 2025-05-25
 */
@Service
@Slf4j
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService {

    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Autowired
    private IDeviceService deviceService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 查询设备数据表
     *
     * @param id 设备数据表主键
     * @return 设备数据表
     */
    @Override
    public DeviceData selectDeviceDataById(Integer id) {
        return getById(id);
    }

    /**
     * 查询设备数据列表
     *
     * @param dto
     */

    /**
     * 查询设备数据列表
     */
    @Override
    public Page selectDeviceDataList(DeviceDataPageReqDto dto) {
        Page<DeviceData> page = this.lambdaQuery()
                .eq(StringUtils.isNotBlank(dto.getDeviceId()), DeviceData::getIotId, dto.getDeviceId())
                .eq(StringUtils.isNotBlank(dto.getDeviceName()), DeviceData::getDeviceName, dto.getDeviceName())
                .eq(StringUtils.isNotBlank(dto.getFunctionId()), DeviceData::getFunctionId, dto.getFunctionId())
                .between(dto.getStartTime() != null && dto.getEndTime() != null, DeviceData::getAlarmTime, dto.getStartTime(), dto.getEndTime())
                .orderByDesc(DeviceData::getAlarmTime)
                .page(new Page<>(dto.getPageNum(), dto.getPageSize()));
        return page;
    }

    /**
     * 新增设备数据表
     *
     * @param deviceData 设备数据表
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData) {
        return save(deviceData) ? 1 : 0;
    }

    /**
     * 修改设备数据表
     *
     * @param deviceData 设备数据表
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData) {
        return updateById(deviceData) ? 1 : 0;
    }

    /**
     * 批量删除设备数据表
     *
     * @param ids 需要删除的设备数据表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Integer[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备数据表信息
     *
     * @param id 设备数据表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Integer id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 将获取到的设备上报数据进行解析，批量保存到设备数据表中
     *
     * @param contentStr
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void handleMessage(String contentStr) {
        /*
        +-------------------+
        |       Root        |
        +-------------------+
                 |
                 v
        +-------------------+
        |   notify_data     |
        +-------------------+
                 |
                 +-------------------+
                 |                   |
                 v                   v
        +-------------------+  +-------------------+
        |      header       |  |       body        |
        +-------------------+  +-------------------+
                 |                   |
                 v                   v
        +-------------------+  +-------------------+
        |   app_id          |  |    services       |
        |   device_id       |  +-------------------+
        |   node_id         |           |
        |   product_id      |           v
        |   gateway_id      |  +-------------------+
        +-------------------+  | service_id        |
                               | properties        |
                               | event_time        |
                               +-------------------+
        */
        // 1.判断数据是否为空
        if (StringUtils.isBlank(contentStr)) {
            throw new RuntimeException("数据为空");
        }

        JSONObject message = JSONUtil.parseObj(contentStr);
        JSONObject notifyDataObj = message.getJSONObject("notify_data");
        if (ObjectUtil.isEmpty(notifyDataObj)) {
            throw new RuntimeException("获取notify_data为空");
        }

        JSONObject header = notifyDataObj.getJSONObject("header");
        JSONObject body = notifyDataObj.getJSONObject("body");

        if (ObjectUtil.isEmpty(header) || ObjectUtil.isEmpty(body)) {
            throw new RuntimeException("获取header或body为空");
        }

        // 2.解析每层数据
        IotMsgNotifyData notifyData = JSONUtil.toBean(notifyDataObj, IotMsgNotifyData.class);
        // 解析成设备Id
        String deviceId = notifyData.getHeader().getDeviceId();

        // 3.判断设备是否存在
        Device device = deviceService.lambdaQuery().eq(Device::getIotId, deviceId).one();
        if (ObjectUtil.isEmpty(device)) {
            log.info("查询设备设备不存在{}171行", deviceId);
            throw new RuntimeException("查询设备设备不存在");
        }

        // 4.设备数据封装
        List<IotMsgService> services = notifyData.getBody().getServices();
        if (CollUtil.isEmpty(services)) {
            log.info("获取services为空178行");
            throw new RuntimeException("获取services为空");
        }

        List<DeviceData> deviceDataList = new ArrayList<>();

        services.forEach(x -> {
            String eventTime = x.getEventTime();
            //设备上报数据的时间
            LocalDateTime alarmTime = OffsetDateTime.parse(eventTime, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX")).atZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();

            Map<String, Object> properties = x.getProperties();
            properties.forEach((key, value) -> {
                DeviceData data = new DeviceData();
                BeanUtils.copyProperties(device, data);
                // 必须设置设备Id为空否则插入失败
                data.setId(null);
                // 功能名（设备物模型属性名）
                data.setFunctionId(key);
                // 物模型属性值
                data.setDataValue(String.valueOf(value));
                // 上报时间
                data.setAlarmTime(alarmTime);
                // 绑定位置（接入位置）
                data.setAccessLocation(device.getBindingLocation());

                deviceDataList.add(data);

            });

        });

        //4. 批量保存数据
        if (CollUtil.isNotEmpty(deviceDataList)) {
            boolean result = this.saveBatch(deviceDataList);
            if (!result) {
                throw new BaseException("批量保存设备上报数据异常");
            }
            log.info("批量保存设备上报数据成功，本地保存成功{}条", deviceDataList.size());

            //5. 将设备最后一次上报的数据更新到Redis（Hash类型）
            redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA, deviceId, JSONUtil.toJsonStr(deviceDataList));
        }
    }
}
